package com.ruoyi.miniapp.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.SystemRoleConstants;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.miniapp.ali.AliOcrUtil;
import com.ruoyi.miniapp.ali.TempFileUtil;
import com.ruoyi.miniapp.config.AliInfoProperty;
import com.ruoyi.miniapp.config.AppInfoProperty;
import com.ruoyi.miniapp.config.DepartConfig;
import com.ruoyi.miniapp.domain.BasAdvertiser;
import com.ruoyi.miniapp.domain.BasMaintainer;
import com.ruoyi.miniapp.domain.FraFranchisees;
import com.ruoyi.miniapp.dto.RealNameDto;
import com.ruoyi.miniapp.mongo.WxUserHandler;
import com.ruoyi.miniapp.mongo.WxUserPointRecordHandler;
import com.ruoyi.miniapp.service.IBasAdvertiserService;
import com.ruoyi.miniapp.service.IBasMaintainerService;
import com.ruoyi.miniapp.service.IFraFranchiseesService;
import com.ruoyi.miniapp.service.IRealNameAuthInfoService;
import com.ruoyi.miniapp.util.IdempotentUtils;
import com.ruoyi.system.api.RemoteSmsService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.RealNameAuthInfo;
import com.tdd.adm.service.feign.MonitorServerFeignClient;
import com.tdd.monitor.entity.RestResult;
import com.tdd.wx.users.api.WxUserServiceApi;
import com.tdd.wx.users.entity.WxUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Api(tags = "小程序用户接口")
@RequestMapping("/wxuser")
@Log4j2
public class WxUserContriller extends BaseController{

    @Autowired
    private WxUserHandler wxUserHandler;
    @Autowired
    private IRealNameAuthInfoService realNameAuthInfoService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private RemoteSmsService remoteSmsService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IBasMaintainerService basMaintainerService;
    @Autowired
    private IBasAdvertiserService basAdvertiserService;
    @Autowired
    private IFraFranchiseesService fraFranchiseesService;
    @Autowired
    private WxUserPointRecordHandler wxUserPointRecordHandler;
    @Autowired
    private AppInfoProperty appInfoProperty;
    @Autowired
    private AliInfoProperty aliInfoProperty;
    @Autowired
    private DepartConfig departConfig;

    //    @Autowired
    //    AdmBusinessFeignClient admBusinessClient;

    @Autowired
    MonitorServerFeignClient monitorServerClient;
    //    @Autowired
    //    AdmStatusFeignClient admStatusClient;

    //    @DubboReference(version = "1.0.0" , interfaceClass = MonitorServerServiceApi.class, interfaceName = "MonitorServerService" , lazy = true, check = false)
    //    private MonitorServerServiceApi monitorServerServiceApi;

    @DubboReference(version = "3.0.0", interfaceClass = WxUserServiceApi.class, interfaceName = "WxUserService", lazy = true, check = false)
    private WxUserServiceApi wxUserServiceApi;

    @ApiOperation("小程序当前登录用户信息")
    @GetMapping("userInfo")
    public R userInfo(){
        Map rtMap = new HashMap<>();
        String unionId = SecurityUtils.getUnionId();
        if(StrUtil.isEmpty(unionId)){
            return R.fail("获取用户信息失败！");
        }
        WxUser wxUser = wxUserHandler.newFindByUnionId(unionId);
        rtMap.put("wxUser", wxUser);
        List<RealNameAuthInfo> list = realNameAuthInfoService.findByUnionId(wxUser.getUnionId());
        if(list.size() > 0){
            Set<Long> roles = list.stream().map(RealNameAuthInfo::getRoleType).collect(Collectors.toSet());
            rtMap.put("roles", roles);
        }
        return R.ok(rtMap);
    }

    @ApiOperation("查看认证信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "roleType", value = "认证类型", dataType = "Long", paramType = "query")})
    @GetMapping("findRealAuthInfo")
    public R findRealAuthInfo(Long roleType){
        String unionId = SecurityUtils.getUnionId();
        return R.ok(realNameAuthInfoService.findByUnionIdAndType(unionId, roleType));
    }

    @GetMapping("findByUnionIdAndType")
    public R<RealNameAuthInfo> findByUnionIdAndType(String unionid, Long roleType){
        return R.ok(realNameAuthInfoService.findByUnionIdAndType(unionid, roleType));
    }


    @ApiOperation("认证")
    @PostMapping("realNameAuth")
    public R realNameAuth(@RequestBody RealNameDto dto){

        try{
            RealNameAuthInfo realNameAuthInfo = BeanUtil.copyProperties(dto, RealNameAuthInfo.class);
            String unionId = SecurityUtils.getUnionId();
            WxUser wxUser = wxUserHandler.newFindByUnionId(unionId);
            Long userId = null;
            if(wxUser == null){
                return R.fail("该微信用户信息不存在");
            }
            log.info("认证校验验证码");
            //校验验证码
            R<Boolean> checkCodeRes = remoteSmsService.checkVerificationCode(dto.getTel(), dto.getCode(), SecurityConstants.INNER);
            boolean checkFlag = checkCodeRes.getData();
            if(! checkFlag){
                return R.fail("验证码不正确！");
            }

            RealNameAuthInfo findR = realNameAuthInfoService.findByUnionIdAndType(unionId, realNameAuthInfo.getRoleType());
            log.info("认证====是否认证====》" + JSONUtil.toJsonStr(findR));

            //验证身份证正面
            if(StrUtil.isNotEmpty(dto.getCardPositive())){
                InputStream ins = TempFileUtil.buildInputStream(dto.getCardPositive());
                TempFileUtil fileUtils = TempFileUtil.getInstance(aliInfoProperty.getAccessKeyId(), aliInfoProperty.getAccessKeySecret(), aliInfoProperty.getRegionId());
                String ossTempFileUrl = fileUtils.upload(ins);
                log.info("身份证正面识别的url:{}",ossTempFileUrl);
                Map map = AliOcrUtil.recognizeIdentityCardFace(aliInfoProperty.getAccessKeyId(), aliInfoProperty.getAccessKeySecret(), ossTempFileUrl);
                if(map == null){
                    return R.fail("身份验证失败，请上传真实身份证照片！");
                }
                String name = MapUtil.getStr(map, "name", null);
                String card = MapUtil.getStr(map, "card", null);
                if(! dto.getRealName().equals(name) || ! dto.getIdCard().equals(card)){
                    return R.fail("身份验证失败，请上传真实身份证照片！");
                }
            }

            List<RealNameAuthInfo> byCardList = realNameAuthInfoService.findByIdCard(dto.getIdCard());
            if(byCardList.size() > 0){
                List<String> unionids = byCardList.stream().map(RealNameAuthInfo::getUnionid).collect(Collectors.toList());
                if(unionids.size() > 0 && ! unionids.contains(unionId)){
                    return R.fail("身份信息被占用!");
                }
            }

            if(findR != null){
                return R.fail("已认证");
            }
//            // 保证 未认证  key不存在
//            IdempotentUtils.remove(SecurityUtils.getUnionId() + "" + dto.getRoleType());
//            // 如果该角色没有认证 才需要 判断是否是重复提交
//            if(! IdempotentUtils.judge(SecurityUtils.getUnionId() + "" + dto.getRoleType(), this.getClass())){
//                return R.fail(1001, "请勿重复提交");
//            }
//            if(wxUser != null && wxUser.getSysUserId() == null){
            if(wxUser.getSysUserId() == null){
//                R<SysUser> result = remoteUserService.findByUnionid(unionId, SecurityConstants.INNER);
//                SysUser sysUser = result.getData();
//                log.info("查询到的当前的系统账号的信息....." + new Gson().toJson(sysUser));
//                if(sysUser == null){
//                    sysUser = new SysUser();
                SysUser sysUser = new SysUser();
                sysUser.setUserName(wxUser.getPhone());
                sysUser.setPhonenumber(wxUser.getPhone());
                sysUser.setNickName(wxUser.getNickName());
                if(StrUtil.isNotEmpty(wxUser.getGener())){
                    switch(wxUser.getGener()){
                        case "0":
                            sysUser.setSex("2");
                            break;
                        case "1":
                            sysUser.setSex("0");
                            break;
                        case "2":
                            sysUser.setSex("1");
                            break;
                        default:
                            sysUser.setSex("2");
                            break;
                    }
                }
                sysUser.setSex(wxUser.getGener());
                sysUser.setAvatar(wxUser.getAvatar());
                sysUser.setUnionId(wxUser.getUnionId());
//                sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPhonenumber()));
                sysUser.setPassword(dto.getIdCard().substring(dto.getIdCard().length()-6));
                sysUser.setStatus("1");
                if(realNameAuthInfo.getRoleType() == 10){
                    sysUser.setRoleIds(new Long[]{SystemRoleConstants.MAINTAINER_ROLE_ID});
                    sysUser.setPostIds(new Long[]{6L});
                    sysUser.setDeptId(SystemRoleConstants.MAINTAINER_DEPT_ID);
                }else if(realNameAuthInfo.getRoleType() == 20){
                    sysUser.setRoleIds(new Long[]{SystemRoleConstants.FRANCHISEES_ROLE_ID});
                    sysUser.setPostIds(new Long[]{8L});
                    sysUser.setDeptId(SystemRoleConstants.FRANCHISEES_DEPT_ID);
                }else if(realNameAuthInfo.getRoleType() == 30){
                    sysUser.setRoleIds(new Long[]{SystemRoleConstants.ADVERTISING_ROLE_ID});
                    sysUser.setPostIds(new Long[]{9L});
                    sysUser.setDeptId(SystemRoleConstants.ADVERTISING_DEPT_ID);
                }
                //                    R<SysUser> regRes = remoteUserService.newregisterUserInfo(sysUser, SecurityConstants.INNER);
                //                    sysUser = regRes.getData();
                Long departId = departConfig.getDepartId(sysUser.getRoleIds());
                sysUser.setDeptId(departId);
                R<SysUser> res = remoteUserService.addSysUser(sysUser);
                log.info("新增的系统用户的信息为..." + new Gson().toJson(res.getData()));
                userId = res.getData().getUserId();
                log.info("新增的系统用户的ID:{}",userId);
                wxUser.setSysUserId(userId);
                SecurityContextHolder.setUserId(userId.toString());
                log.info("新增的系统用户的SecurityContextHolder.getUserId:{}",SecurityUtils.getUserId());
//                }else {
//                    ////////////////////////////
//                    log.info("该用户认证第二个或者第三个角色");
//                    Long[] rols = new Long[sysUser.getRoleIds().length + 1];
//                    System.arraycopy(sysUser.getRoleIds(), 0, rols, 0, sysUser.getRoleIds().length);
//                    if(realNameAuthInfo.getRoleType() == 10){
//                        rols[sysUser.getRoleIds().length] = SystemRoleIdsConstants.MAINTAINER_ROLE_ID;
//                        sysUser.setRoleIds(rols);
//                        sysUser.setPostIds(new Long[]{6L});
//                    }else if(realNameAuthInfo.getRoleType() == 20){
//                        rols[sysUser.getRoleIds().length] = SystemRoleIdsConstants.FRANCHISEES_ROLE_ID;
//                        sysUser.setRoleIds(rols);
//                        sysUser.setPostIds(new Long[]{8L});
//                    }else if(realNameAuthInfo.getRoleType() == 30){
//                        rols[sysUser.getRoleIds().length] = SystemRoleIdsConstants.ADVERTISING_ROLE_ID;
//                        sysUser.setRoleIds(rols);
//                        sysUser.setPostIds(new Long[]{9L});
//                    }
//                    log.info("用户的id：{},角色的数组:{}",sysUser.getUserId(),rols);
//                    remoteUserService.insertAuthRoleByUserId(sysUser.getUserId(),rols);
//                    //////////////////////////

//                }
                //wxUser.setSysUserId(sysUser.getUserId());
                wxUser.setSysUserName(sysUser.getUserName());
                wxUserHandler.updateWxUser(wxUser);
            }else{
                ////////////////////////////
                R<SysUser> result = remoteUserService.findByUnionid(unionId, SecurityConstants.INNER);
                SysUser sysUser = result.getData();
                userId = sysUser.getUserId();
                log.info("查询到的当前的系统账号的信息....." + new Gson().toJson(sysUser));
                    log.info("该用户认证第二个或者第三个角色");
                    log.info("查询出来该系统用户=={}的角色数组为=={}",sysUser.getUserId(),sysUser.getRoleIds());
                    Long[] rols = new Long[sysUser.getRoleIds().length + 1];
                    System.arraycopy(sysUser.getRoleIds(), 0, rols, 0, sysUser.getRoleIds().length);
                    if(realNameAuthInfo.getRoleType() == 10){
                        rols[sysUser.getRoleIds().length] = SystemRoleConstants.MAINTAINER_ROLE_ID;
                        sysUser.setRoleIds(rols);
                        sysUser.setPostIds(new Long[]{6L});
                    }else if(realNameAuthInfo.getRoleType() == 20){
                        rols[sysUser.getRoleIds().length] = SystemRoleConstants.FRANCHISEES_ROLE_ID;
                        sysUser.setRoleIds(rols);
                        sysUser.setPostIds(new Long[]{8L});
                    }else if(realNameAuthInfo.getRoleType() == 30){
                        rols[sysUser.getRoleIds().length] = SystemRoleConstants.ADVERTISING_ROLE_ID;
                        sysUser.setRoleIds(rols);
                        sysUser.setPostIds(new Long[]{9L});
                    }
                    log.info("新增用户的id：{},角色的数组:{}",userId,rols);
                    remoteUserService.insertAuthRoleByUserId(userId,rols);
                    //////////////////////////
            }
            log.info("更新后的wxUser的信息为...." + new Gson().toJson(wxUser));
            realNameAuthInfo.setUnionid(wxUser.getUnionId());
            realNameAuthInfo.setUserId(userId);
            realNameAuthInfoService.save(realNameAuthInfo);
            if(realNameAuthInfo.getRoleType() == 10){
                BasMaintainer basMaintainer = new BasMaintainer();
                basMaintainer.setUserId(userId);
                basMaintainer.setFkUnionId(wxUser.getUnionId());
                basMaintainer.setDtMaintainerType(realNameAuthInfo.getAuthType() == 1 ? 2 : 1);
                basMaintainer.setServerVillageAmount(0);
                basMaintainer.setFkOrgCode(realNameAuthInfo.getCompanyNumber());
                basMaintainerService.saveOrUpdate(basMaintainer);
            }else if(realNameAuthInfo.getRoleType() == 20){
                FraFranchisees fraFranchisees = new FraFranchisees();
                fraFranchisees.setUserId(userId);
                fraFranchisees.setFkUnionId(wxUser.getUnionId());
                fraFranchisees.setFranchiseeTypeNo(realNameAuthInfo.getAuthType() == 1 ? 2 : 1);
                fraFranchisees.setAdmAmount(0);
                fraFranchisees.setFkOrgCode(realNameAuthInfo.getCompanyNumber());
                fraFranchiseesService.saveOrUpdate(fraFranchisees);
            }else if(realNameAuthInfo.getRoleType() == 30){
                BasAdvertiser basAdvertiser = new BasAdvertiser();
                basAdvertiser.setUserId(userId);
                basAdvertiser.setFkUnionId(wxUser.getUnionId());
                basAdvertiser.setFkOrgCode(realNameAuthInfo.getCompanyNumber());
                basAdvertiserService.saveOrUpdate(basAdvertiser);
            }
        }catch(Exception e){
            log.error("认证异常！===》" + e.getMessage(), e);
            return R.fail("认证失败！");
        }
        return R.ok();
    }

    @ApiOperation("getBag")
    @GetMapping("getBag")
    public R getBag(String keyStr){
        //        tdd_ad_client://GBK20220109?t=UV1JTDT2MUH
        //        https://www.tddst.com/q/T200;FFF
        log.debug("开始取袋子....");
        if(! IdempotentUtils.judge(keyStr, this.getClass())){
            return R.fail(1001, "请勿重复提交,请过10秒再试！");
        }

        String key = URLUtil.decode(keyStr);
        Map rtMap = new HashMap();
        String unionid = SecurityUtils.getUnionId();
        WxUser wxUser = wxUserHandler.findByUnionId(unionid);
        log.debug("1-开始取袋子....");
        String admCode = null;
        String timer = null;
        try{
            //            String tempStr = key.replace("tdd_ad_client://","").replace("?t","");
            //            admCode = tempStr.split("=")[0];
            //            timer = tempStr.split("=")[1];
            log.debug("2-开始取袋子....");
            String tempStr = key.replace("https://www.tddst.com/q/", "");
            admCode = tempStr.split(";")[0];
            timer = tempStr.split(";")[1];
            rtMap.put("admCode", admCode);
            log.debug("3-开始取袋子....");
        }catch(Exception e){
            log.error("解析二维码错误==》" + e.getMessage());
            rtMap.put("admCode", admCode);
            rtMap.put("msg", "二维码格式错误！");
            return R.fail(rtMap);
        }
        try{
            //可取袋子数量
            log.debug("4-开始取袋子....");
            int num = wxUserServiceApi.getUserBagLeft(wxUser.getUnionId(), admCode);
            if(num <= 0){
                log.debug("5-开始取袋子....");
                rtMap.put("admCode", admCode);
                rtMap.put("msg", "今日袋子已领完！");
                return R.fail(rtMap);
            }
            log.debug("6-开始取袋子....");

            //查询出袋状态
            //            RestResult res1 = monitorServerServiceApi.state_CmdStatus(timer,admCode);
            RestResult res1 = monitorServerClient.state_CmdStatus(timer, admCode);
            //            RestResult res = monitorServerServiceApi.cmd_GiveOutBag(admCode,wxUser.getUnionId(),timer,1);
            RestResult res = monitorServerClient.cmd_GiveOutBag(admCode, wxUser.getUnionId(), timer, 1);
            log.info("取袋服务调用返回==》" + JSONUtil.toJsonStr(res));
            log.debug("7-开始取袋子....");
            if(res.getCode() == 200){
                log.info("取袋服务-放入缓存==》key==>" + "getBagCode_" + admCode + "_" + timer + "===value==>" + res.getValue());
                redisService.setCacheObject("getBagCode_" + admCode + "_" + timer, res.getValue(), 15L, TimeUnit.SECONDS);
                rtMap.put("msg", "请求成功！");
            }else {
                log.debug("8-开始取袋子....");
                rtMap.put("admCode", admCode);
                rtMap.put("msg", "服务调用失败！");
                return R.fail(rtMap);
            }
        }catch(Exception e){
            log.error("出袋异常==》" + e.getMessage());
            rtMap.put("admCode", admCode);
            rtMap.put("msg", "出袋异常，请稍后再试！");
            return R.fail(rtMap);
        }
        log.debug("9-开始取袋子....ret：{}", rtMap);
        return R.ok(rtMap);
    }

    @ApiOperation("扫码获取admCode")
    @GetMapping("keyToAdmCode")
    public R keyToAdmCode(String keyStr){
        try{
            String key = URLUtil.decode(keyStr);
            //            String tempStr = key.replace("tdd_ad_client://","").replace("?t","");
            //            String admCode = tempStr.split("=")[0];
            String tempStr = key.replace("https://www.tddst.com/q/", "");
            String admCode = tempStr.split(";")[0];
            return R.ok(admCode);
        }catch(Exception e){
            return R.fail("解析失败！");
        }
    }

    @GetMapping("getBagState")
    @ApiOperation("查询取袋状态")
    public R getBagState(String keyStr){
        Map rtMap = new HashMap();
        try{
            synchronized(keyStr) {
                log.debug("1-查询状态....");
                String unionid = SecurityUtils.getUnionId();
                WxUser wxUser = wxUserHandler.findByUnionId(unionid);
                String key = URLUtil.decode(keyStr);
                log.debug("2-查询状态....{}", keyStr);
                //                String tempStr = key.replace("tdd_ad_client://","").replace("?t","");
                //                String admCode = tempStr.split("=")[0];
                //                String timer = tempStr.split("=")[1];
                String tempStr = key.replace("https://www.tddst.com/q/", "");
                String admCode = tempStr.split(";")[0];
                String timer = tempStr.split(";")[1];
                log.debug("3-查询状态....");
                log.info("取袋状态进入-查询缓存==》key==>" + "getBagCode_" + admCode + "_" + timer);
                String stemp = redisService.getCacheObject("getBagCode_" + admCode + "_" + timer);
                log.info("取袋状态进入===>" + stemp);
                if(stemp != null){
                    //查询出袋状态
                    log.debug("4-查询状态....");
                    //                    RestResult res = monitorServerServiceApi.state_CmdStatus(stemp,admCode);
                    RestResult res = monitorServerClient.state_CmdStatus(stemp, admCode);
                    log.info("取袋状态服务调用返回==》" + JSONUtil.toJsonStr(res));
                    if(res == null || ! res.getValue().toString().equals("Done")){
                        return R.fail(2001, "查询失败！");
                    }
                    //取袋子
                    //todo 在其他地方完成 ，在Auth-recordGiveOutBagComplete中，由通讯服务调用
                    //wxUserServiceApi.updateReceiveBagAmount(wxUser.getOpenId(),1);
                    //
                    //记录当天取袋次数  计算到凌晨的时间
                    log.debug("5-查询状态....");
                    DateTime endTime = DateUtil.beginOfDay(DateUtil.tomorrow());
                    //Long betweenSeconds = DateUtil.between(DateTime.now(), endTime, DateUnit.SECOND);
                    //redisService.setCacheObject("get_bag_" + unionid, 1, betweenSeconds, TimeUnit.SECONDS);
                    //加积分
                    //todo 在其他地方完成 ，在Auth-recordGiveOutBagComplete中，由通讯服务调用
                    //wxUserServiceApi.increasePoints(wxUser.getOpenId(),1);
                    //wxUserPointRecordHandler.save(unionid,"领袋子","get_bag", BigDecimal.ONE);
                    redisService.deleteObject("getBagCode_" + admCode + "_" + timer);
                    log.debug("6-查询状态....");
                    rtMap.put("point", wxUser.getUserPoints() == null ? 1 : wxUser.getUserPoints());
                    rtMap.put("addPoint", BigDecimal.ONE);
                    return R.ok(rtMap);
                }else {
                    log.info("取袋状态换成code无");
                    return R.fail(500, "已领取或已过期");
                }
            }
        }catch(Exception e){
            log.info(e.getMessage());
            e.printStackTrace();
            return R.fail("查询失败！");
        }
    }

    @ApiOperation("app下载信息参数")
    @GetMapping("appDownInfo")
    public R appDownInfo(){
        Map rtMap = new HashMap();
        rtMap.put("url", appInfoProperty.getAppDownloadUrl());
        rtMap.put("contacts", appInfoProperty.getContacts());
        rtMap.put("qrCode", QrCodeUtil.generateAsBase64(appInfoProperty.getAppDownloadUrl(), QrConfig.create().setHeight(300).setWidth(300), "jpeg"));
        return R.ok(rtMap);
    }

    @ApiOperation("获取默认取代次数")
    @GetMapping("getCanGetBagNum")
    public R getCanGetBagNum(){
        String unionid = SecurityUtils.getUnionId();
        int num = wxUserServiceApi.getUserBagLeft(unionid, null);
//        if(num<=0)
        {
            return R.ok(num);
        }
//        Integer getNum = null;
//        try{
//            getNum = Integer.valueOf(redisService.getCacheObject("get_bag_" + unionid));
//        }catch(Exception e){
//            getNum = 0;
//            log.debug("没取到：", e);
//        }
//        return R.ok(num - getNum);
    }

}
